package cn.com.lms.business.cc.controller;

import cn.com.lms.business.cc.vo.ExamQuestionVO;
import cn.com.lms.business.cc.service.CCQuestionCategoryService;
import cn.com.lms.business.cc.service.CCQuestionService;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;
import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.webmvc.util.WebMvcUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("cc/exam/question")
public class CCQuestionController {

    @Autowired
    CCQuestionService questionService;

    @Autowired
    CCQuestionCategoryService questionCategoryService;

    @GetMapping("/page")
    public ResponseResult<Page<ExamQuestionVO>> getQuestionPage(HttpServletRequest request){
        //获取查询条件
        // KeyWord: 按关键字模糊查询
        // CategoryId: 按分类id查询
        String key = request.getParameter("KeyWord");
        String categoryId = request.getParameter("CategoryId");

        //分页
        QueryHelpBean queryHelpBean = questionService.getQueryHelpBean();
        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "eq.create_time"));
        queryHelpBean.setPageable(pageable);
        //eq.is_delete 为false
        IExpression build = CompareExpression.build("eq.is_delete", CompareType.equal, false);
        queryHelpBean.addWhere(build);

        //判断key 是否为空
        if(!StringUtils.isEmpty(key)){
            IExpression build1 = CompareExpression.build("eq.question_name", CompareType.like, key);
            queryHelpBean.addWhere(build1);
        }

        //判断树
        if(!StringUtils.isEmpty(categoryId) && !categoryId.equals(0)){
            List<Long> childrenIds = questionCategoryService.findChildrensIdByCategoryId(categoryId);
            childrenIds.add(Long.valueOf(categoryId));
            IExpression build2 = CompareExpression.build("eq.category_id", CompareType.in, childrenIds);
            queryHelpBean.addWhere(build2);
        }
        Page<ExamQuestionVO> all = questionService.findAll(queryHelpBean);
        return ResponseResult.success(all);

    }

}
